// * 2、 获取蓝牙适配器状态，判断设备蓝牙是否可用。
// * 3、 判断蓝牙适配器可用时开启扫描蓝牙设备和开启获取已连接的蓝牙设备
// * 4、 如果开启扫描蓝牙设备失败5s后自动再次开启扫描
// * 5、 开启扫描蓝牙设备成功后开启监听已扫描的设备
// * 6、 如果已扫描到的新设备含FeiZhi名（个人产品需要）的设备则开始连接该设备
// * 7、 开启获取已连接蓝牙设备开启获取设备成功后判断以获取的设备名包含FeiZhi（个人产品需要）字符串的设备则开始连接该设备
// * 8、 开始获取已连接蓝牙设备没有成功获取到已连接的蓝牙设备5s后自动重新开启获取。
// * 9、 开始连接某设备时停止扫描设备，停止循环获取已连接设备。
// * 10、连接成功后停止扫描设备，停止循环获取已连接设备。
Page({
  /*** 页面的初始数据*/
  data: {
    serviceId:null,
    imgUrls: ['','',''],
    indicatorDots: true,
    autoplay: false,
    interval: 5000,
    duration: 1000,
    switchH:0,
    deviceId:'',
    getConnectedTimer:null,
    discoveryDevicesTimer:null,
    isConnectting:false,
    connectDeviceIndex:0,
    isAlert:true
  },
  catchswitch:function(){
    wx.navigateTo({
      url: '../data/data',
    })
  },
  onLoad: function(options) {
    let that = this,
        swiper =0;
    let query = wx.createSelectorQuery();
    //选择id
    query.select('#swiper').boundingClientRect(function (rect) {
      swiper = rect.height;
      wx.getSystemInfo({
        success: function (res) {
          // 获取可使用窗口宽度
          let clientHeight = res.windowHeight;
          let clientWidth = res.windowWidth;
          that.setData({
            switchH: clientHeight - swiper - (clientWidth / 750 * 20)
          });
        }
      });
    }).exec();
    // 获取系统信息
  },
  startConnect: function() {
    let that = this;
    wx.showLoading({
      title: '开启蓝牙适配'
    });
    //初始化微信小程序蓝牙适配器
    wx.openBluetoothAdapter({
      success: function(res) {
        wx.hideLoading()
        console.log("初始化蓝牙适配器");
        setTimeout(()=>{  //  IOS里面蓝牙状态变化以后不能马上开始搜索，否则会搜索不到设备，必须要等待2秒以上。
          that.getBluetoothAdapterState();
        },2000)
        
      },
      fail: function(err) {
        wx.hideLoading
        wx.showToast({
          title: '蓝牙初始化失败',
          icon: 'success',
          duration: 2000
        })
        setTimeout(function() {
          wx.hideToast()
        }, 2000)
      }
    });
    wx.onBluetoothAdapterStateChange(function(res) {
      let available = res.available;
      if (available) {
        setTimeout(()=>{  //  IOS里面蓝牙状态变化以后不能马上开始搜索，否则会搜索不到设备，必须要等待2秒以上。
          that.getBluetoothAdapterState();
        },2000)
      }
    })
  },
  //获取本机蓝牙适配器状态
  getBluetoothAdapterState: function() {
    let that = this;
    wx.getBluetoothAdapterState({
      success: function(res) {
        let available = res.available,
          discovering = res.discovering;
        if (!available) {
          wx.showToast({
            title: '设备无法开启蓝牙连接',
            icon: 'success',
            duration: 2000
          })
          setTimeout(function() {
            wx.hideToast()
          }, 2000)
        } else {
          if (!discovering) {
            console.log('获取适配器状态成功')
            that.startBluetoothDevicesDiscovery();
            // that.getConnectedBluetoothDevices();
          }
        }
      },
      fail:res=>{
        console.log(res)
      }
    })
  },
  //搜索周边的蓝牙设备
  startBluetoothDevicesDiscovery: function() {
    let that = this;
    wx.showLoading({
      title: '蓝牙搜索'
    });
    wx.startBluetoothDevicesDiscovery({
      services: [],
      allowDuplicatesKey: false,
      success: function(res) {
        console.log('设备--》', res)
        if (!res.isDiscovering) {
          // that.getBluetoothAdapterState();
          that.getBluetoothDevices();
          //获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备
        } 
        else {
          that.onBluetoothDeviceFound();
          //（监听寻找到新设备的事件 ——表示只要找到一个新的蓝牙设备就会调用一次该方法）
        }
      },
      fail: function(err) {
        console.log(err);
      }
    });
  },
  getBluetoothDevices(){
    wx.getBluetoothDevices({
      success(res) {
        console.log('00',res)
        if (res.devices[0]) {
          console.log('111',ab2hex(res.devices[0].advertisData))
        }
      }
    })
  },
  ab2hex(buffer) {
    const hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
    return hexArr.join('')
  },
  getConnectedBluetoothDevices: function() {
    let that = this;
    wx.getConnectedBluetoothDevices({
      services: [that.serviceId],
      success: function(res) {
        console.log("获取处于连接状态的设备", res);
        let devices = res['devices'],
          flag = false,
          index = 0,
          conDevList = [];
        devices.forEach(function(value, index, array) {
          if (value['name'].indexOf('FeiZhi') != -1) {
            // 如果存在包含FeiZhi字段的设备
            flag = true;
            index += 1;
            conDevList.push(value['deviceId']);
            that.setData({
              deviceId:value['deviceId']
            })
            // that.deviceId = value['deviceId'];
            return;
          }
        });
        if (flag) {
          this.data.connectDeviceIndex = 0;
          that.loopConnect(conDevList);
        } else {
          if (!this.data.getConnectedTimer) {
            that.data.getConnectedTimer = setTimeout(function() {
              that.getConnectedBluetoothDevices();
            }, 5000);
          }
        }
      },
      fail: function(err) {
        if (!this.data.getConnectedTimer) {
          that.data.getConnectedTimer = setTimeout(function() {
            that.getConnectedBluetoothDevices();
          }, 5000);
        }
      }
    });
  },
  onBluetoothDeviceFound: function() {
    let that = this;
    console.log('onBluetoothDeviceFound');
    wx.onBluetoothDeviceFound(function(res) {
      console.log('new device list has founded')
      console.log(res);
      if (res.devices[0]) {
        let name = res.devices[0]['name'];
        if (name != '') {
          if (name.indexOf('Mi_Watch') != -1) {
            let deviceId = res.devices[0]['deviceId'];
            // that.deviceId = deviceId;
            that.setData({
              deviceId:deviceId
            })
            console.log(that.data.deviceId);
            that.startConnectDevices();
          }
        }
      }
    })
  },
  startConnectDevices(ltype, array) {
    let that = this;
    clearTimeout(that.data.getConnectedTimer);
    that.data.getConnectedTimer = null;
    clearTimeout(that.data.discoveryDevicesTimer);
    wx.stopBluetoothDevicesDiscovery();
    this.data.isConnectting = true;
    wx.createBLEConnection({
      deviceId: that.data.deviceId,
      success: function(res) {
        if (res.errCode == 0) {
          setTimeout(function() {
            that.getService(that.deviceId);
          }, 5000)
        }
      },
      fail: function(err) {
        console.log('连接失败：', err);
        if (ltype == 'loop') {
          // that.connectDeviceIndex += 1;
          that.setData({
            connectDeviceIndex:that.data.connectDeviceIndex += 1
          })
          that.loopConnect(array);
        } else {
          that.startBluetoothDevicesDiscovery();
          that.getConnectedBluetoothDevices();
        }
      },
      complete: function() {
        console.log('complete connect devices');
        this.data.isConnectting = false;
      }
    });
  },
  getService: function(deviceId) {
    let that = this;
    // 监听蓝牙连接
    wx.onBLEConnectionStateChange(function(res) {
      console.log(res);
    });
    // 获取蓝牙设备service值
    wx.getBLEDeviceServices({
      deviceId: deviceId,
      success: function(res) {
        that.getCharacter(deviceId, res.services);
      }
    })
  },
  getCharacter: function(deviceId, services) {
    let that = this;
    services.forEach(function(value, index, array) {
      if (value == that.data.serviceId) {
        // that.serviceId = array[index];
        that.setData({
          serviceId:array[index]
        })
      }
    });
    wx.getBLEDeviceCharacteristics({
      deviceId: deviceId,
      serviceId: that.data.serviceId,
      success: function(res) {
        that.writeBLECharacteristicValue(deviceId, that.data.serviceId, that.data.characterId_write);
        that.openNotifyService(deviceId, that.data.serviceId, that.data.characterId_read);
      },
      fail: function(err) {
        console.log(err);
      },
      complete: function() {
        console.log('complete');
      }
    })
  },
  loopConnect: function(devicesId) {
    let that = this;
    let listLen = devicesId.length;
    if (devicesId[this.connectDeviceIndex]) {
      this.deviceId = devicesId[this.connectDeviceIndex];
      this.startConnectDevices('loop', devicesId);
    } else {
      console.log('已配对的设备小程序蓝牙连接失败');
      that.startBluetoothDevicesDiscovery();
      that.getConnectedBluetoothDevices();
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})